<template>
  <div class="elderly-detail">
    <div class="page-header">
      <el-button @click="$router.back()" icon="ArrowLeft">返回</el-button>
      <h2>{{ elderly?.name }} - 档案详情</h2>
    </div>
    
    <el-row :gutter="20">
      <!-- 基本信息 -->
      <el-col :span="8">
        <el-card class="info-card">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <el-button type="primary" size="small" @click="editBasicInfo">编辑</el-button>
            </div>
          </template>
          
          <div v-if="elderly" class="info-content">
            <div class="info-item">
              <label>姓名：</label>
              <span>{{ elderly.name }}</span>
            </div>
            <div class="info-item">
              <label>年龄：</label>
              <span>{{ elderly.age }}岁</span>
            </div>
            <div class="info-item">
              <label>性别：</label>
              <span>{{ elderly.sex }}</span>
            </div>
            <div class="info-item">
              <label>联系电话：</label>
              <span>{{ elderly.phone }}</span>
            </div>
            <div class="info-item">
              <label>地址：</label>
              <span>{{ elderly.address }}</span>
            </div>
            <div class="info-item">
              <label>身高：</label>
              <span>{{ elderly.height }}</span>
            </div>
            <div class="info-item">
              <label>体重：</label>
              <span>{{ elderly.weight }}</span>
            </div>
            <div class="info-item">
              <label>血型：</label>
              <span>{{ elderly.bloodType }}</span>
            </div>

            <el-divider content-position="left">紧急联系人</el-divider>
            <div class="info-item">
              <label>姓名：</label>
              <span>{{ elderly.emergencyContact.name }}</span>
            </div>
            <div class="info-item">
              <label>电话：</label>
              <span>{{ elderly.emergencyContact.phone }}</span>
            </div>
            <div class="info-item">
              <label>关系：</label>
              <span>{{ elderly.emergencyContact.relationship }}</span>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <!-- 健康记录 -->
      <el-col :span="16">
        <el-card class="health-card">
          <template #header>
            <div class="card-header">
              <span>健康记录</span>
              <el-button type="primary" size="small" @click="showHealthDialog = true">
                添加记录
              </el-button>
            </div>
          </template>
          
          <div class="health-charts">
            <el-row :gutter="20">
              <el-col :span="12">
                <div ref="bloodPressureChart" class="chart-container"></div>
              </el-col>
              <el-col :span="12">
                <div ref="bloodSugarChart" class="chart-container"></div>
              </el-col>
            </el-row>
          </div>
          
          <el-table :data="healthRecords" style="width: 100%; margin-top: 20px">
            <el-table-column prop="date" label="日期" width="120" />
            <el-table-column label="血压" width="120">
              <template #default="{ row }">
                {{ row.systolic }}/{{ row.diastolic }}
              </template>
            </el-table-column>
            <el-table-column prop="bloodSugar" label="血糖" width="80" />
            <el-table-column prop="weight" label="体重(kg)" width="100" />
            <el-table-column prop="temperature" label="体温(°C)" width="100" />
            <el-table-column prop="heartRate" label="心率" width="80" />
            <el-table-column prop="notes" label="备注" show-overflow-tooltip />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 用药记录 -->
    <el-card class="medication-card" style="margin-top: 20px">
      <template #header>
        <div class="card-header">
          <span>用药记录</span>
          <el-button type="primary" size="small" @click="showMedicationDialog = true">
            添加记录
          </el-button>
        </div>
      </template>
      
      <el-table :data="medicationRecords" style="width: 100%">
        <el-table-column prop="date" label="日期" width="120" />
        <el-table-column prop="medicationName" label="药品名称" width="150" />
        <el-table-column prop="dosage" label="剂量" width="100" />
        <el-table-column prop="frequency" label="频次" width="100" />
        <el-table-column prop="duration" label="疗程" width="100" />
        <el-table-column prop="notes" label="备注" show-overflow-tooltip />
        <el-table-column label="操作" width="120">
          <template #default="{ row }">
            <el-button size="small" type="danger" @click="deleteMedication(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 基本信息编辑对话框 -->
<el-dialog 
  v-model="showEditDialog"
  title="编辑老人基本信息"
  width="600px"
  :close-on-click-modal="false"
>
  <el-form
    ref="editFormRef"
    :model="elderly"
    label-width="100px"
  >
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="年龄" prop="age">
          <el-input-number
            v-model="editForm.age"
            :min="0"
            :max="150"
            style="width: 100%"
          />
        </el-form-item>
      </el-col>
    </el-row>
<el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="身高" prop="height">
          <el-input v-model="editForm.height" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="体重" prop="weight">
          <el-input
            v-model="editForm.weight" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="血型" prop="weight">
          <el-input
            v-model="editForm.bloodType" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="性别" prop="sex">
          <el-select v-model="editForm.sex" style="width: 100%">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="联系电话" prop="phone">
          <el-input v-model="editForm.phone" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item label="地址" prop="address">
      <el-input v-model="editForm.address" />
    </el-form-item>

    <el-divider content-position="left">紧急联系人</el-divider>
    
    <el-row :gutter="20">
      <el-col :span="12">
        <el-form-item label="姓名" prop="emergencyContact.name">
          <el-input v-model="editForm.emergencyContact.name" />
        </el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="电话" prop="emergencyContact.phone">
          <el-input v-model="editForm.emergencyContact.phone" />
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="关系" prop="emergencyContact.relationship">
      <el-input v-model="editForm.emergencyContact.relationship" />
    </el-form-item>


    <el-divider content-position="left">医疗信息</el-divider>
    <el-form-item label="病史">
      <div class="tags-container">
        <el-tag
          v-for="(history, index) in editForm.medicalHistory"
          :key="index"
          closable
          type="warning"
          @close="removeEditMedicalHistory(index)"
        >
          {{ history }}
        </el-tag>
        <el-input
          v-if="showEditMedicalHistoryInput"
          ref="editMedicalHistoryInputRef"
          v-model="newEditMedicalHistory"
          size="small"
          style="width: 120px"
          @keyup.enter="addEditMedicalHistory"
          @blur="addEditMedicalHistory"
        />
        <el-button v-else size="small" @click="showEditMedicalHistoryInput = true">
          + 添加病史
        </el-button>
      </div>
    </el-form-item>

    <el-form-item label="过敏史">
      <div class="tags-container">
        <el-tag
          v-for="(allergy, index) in editForm.allergies"
          :key="index"
          closable
          type="danger"
          @close="removeEditAllergy(index)"
        >
          {{ allergy }}
        </el-tag>
        <el-input
          v-if="showEditAllergyInput"
          ref="editAllergyInputRef"
          v-model="newEditAllergy"
          size="small"
          style="width: 120px"
          @keyup.enter="addEditAllergy"
          @blur="addEditAllergy"
        />
        <el-button v-else size="small" @click="showEditAllergyInput = true">
          + 添加过敏史
        </el-button>
      </div>
    </el-form-item>
  </el-form>

  <template #footer>
    <el-button @click="showEditDialog = false">取消</el-button>
    <el-button type="primary" @click="saveBasicInfo" :loading="saving">保存</el-button>
  </template>
</el-dialog>
    <!-- 健康记录对话框 -->
    <el-dialog v-model="showHealthDialog" title="添加健康记录" width="500px">
      <el-form ref="healthFormRef" :model="healthForm" :rules="healthRules" label-width="100px">
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="healthForm.date"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="收缩压" prop="systolic">
              <el-input-number
                v-model="healthForm.systolic"
                :min="0"
                :max="300"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="舒张压" prop="diastolic">
              <el-input-number
                v-model="healthForm.diastolic"
                :min="0"
                :max="200"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="血糖" prop="bloodSugar">
              <el-input-number
                v-model="healthForm.bloodSugar"
                :min="0"
                :max="50"
                :precision="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体重(kg)" prop="weight">
              <el-input-number
                v-model="healthForm.weight"
                :min="0"
                :max="200"
                :precision="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="体温(°C)" prop="temperature">
              <el-input-number
                v-model="healthForm.temperature"
                :min="30"
                :max="45"
                :precision="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="心率" prop="heartRate">
              <el-input-number
                v-model="healthForm.heartRate"
                :min="0"
                :max="300"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="healthForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showHealthDialog = false">取消</el-button>
        <el-button type="primary" @click="saveHealthRecord">保存</el-button>
      </template>
    </el-dialog>
    
    <!-- 用药记录对话框 -->
    <el-dialog v-model="showMedicationDialog" title="添加用药记录" width="500px">
      <el-form ref="medicationFormRef" :model="medicationForm" :rules="medicationRules" label-width="100px">
        <el-form-item label="日期" prop="date">
          <el-date-picker
            v-model="medicationForm.date"
            type="date"
            placeholder="选择日期"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="药品名称" prop="medicationName">
          <el-input v-model="medicationForm.medicationName" placeholder="请输入药品名称" />
        </el-form-item>
        
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="剂量" prop="dosage">
              <el-input v-model="medicationForm.dosage" placeholder="如：1片" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="频次" prop="frequency">
              <el-input v-model="medicationForm.frequency" placeholder="如：每日3次" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="疗程" prop="duration">
          <el-input v-model="medicationForm.duration" placeholder="如：7天" />
        </el-form-item>
        
        <el-form-item label="备注" prop="notes">
          <el-input
            v-model="medicationForm.notes"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showMedicationDialog = false">取消</el-button>
        <el-button type="primary" @click="saveMedicationRecord">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, nextTick } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import { useElderlyStore, type Elderly, type HealthRecord, type MedicationRecord } from '@/stores/elderly'
import { updateElderly, deleteElderly, getElderlyById } from '@/api/elderlyInfo/elderlyInfo'
import { he } from 'element-plus/es/locales.mjs'
import { addCheckupData,getALLCheckupDataById } from '@/api/health_checkup_dateinfo/health_checkup_datainfo'
import {addMedicationData,getALLMedicationDataById,deleteMedicationData} from '@/api/medicationinfo/medicationinfo'

const route = useRoute()
const elderlyStore = useElderlyStore()
const showEditDialog = ref(false)
const elderly = ref<Elderly | null>(null);
onMounted(async () => {
  const id = route.params.id as string;
  
  // 先从 store 查找
  const storeData = elderlyStore.elderlyList.find(item => item.id === id);
  if (storeData) {
    elderly.value = storeData;
  } else {
    // 如果没有则从 API 获取
    await fetchElderlyData(id);
  }
  await getHealthRecords();
  getMedicationRecords();
  console.log("测试点1");
  await initCharts();
  console.log("测试点2");
  
});

const fetchElderlyData = async (id: string) => {
  try {
    const response = await getElderlyById(id); // 调用 API
    if (response.code === 200) {
      elderly.value = response.data;
    }
  } catch (error) {
    ElMessage.error('获取老人详情失败');
  }
};

const healthRecords = ref<HealthRecord[]>([]);

const getHealthRecords = async () => {
  try {
    const id = elderly.value?.id;
    if (!id) return;
    const response = await getALLCheckupDataById(id); // 调用 API
    if (response.code === 200) {
      healthRecords.value = response.data;
    }
  } catch (error) {
    ElMessage.error('获取健康记录失败');
  }
};
const medicationRecords = ref<MedicationRecord[]>([]);

const getMedicationRecords = async () => { 
  try {
    const id = elderly.value?.id;
    if (!id) return;
    const response = await getALLMedicationDataById(id); // 调用 API
    if (response.code === 200) {
      medicationRecords.value = response.data;
    }
  } catch (error) {
    ElMessage.error('获取用药记录失败');
  }
};

const showHealthDialog = ref(false)
const showMedicationDialog = ref(false)
const healthFormRef = ref()
const medicationFormRef = ref()

const bloodPressureChart = ref()
const bloodSugarChart = ref()
const editFormRef = ref()
const saving = ref(false)
const showEditMedicalHistoryInput = ref(false)
const showEditAllergyInput = ref(false)
const newEditMedicalHistory = ref('')
const newEditAllergy = ref('')
const editMedicalHistoryInputRef = ref()
const editAllergyInputRef = ref()
const editForm = reactive({
  id: '',
  name: '',
  age: 0,
  sex: '男' as '男' | '女',
  phone: '',
  address: '',
  height: '',
  weight: '',
  bloodType: '',
  emergencyContact: {
    name: '',
    phone: '',
    relationship: ''
  },
  medicalHistory: [] as string[],
  allergies: [] as string[]
})

// 表单验证规则
const elderlyRules = {
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  age: [{ required: true, message: '请输入年龄', trigger: 'blur' }],
  sex: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
  address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
  'emergencyContact.name': [{ required: true, message: '请输入紧急联系人姓名', trigger: 'blur' }],
  'emergencyContact.phone': [{ required: true, message: '请输入紧急联系人电话', trigger: 'blur' }],
  'emergencyContact.relationship': [{ required: true, message: '请输入关系', trigger: 'blur' }]
}

// 打开编辑对话框
const editBasicInfo = () => {
  if (elderly.value) {
    Object.assign(editForm, {
      ...elderly.value,
      // 确保 emergencyContact 有默认值
      emergencyContact: elderly.value.emergencyContact || {
        name: '',
        phone: '',
        relationship: ''
      },
      // 确保数组有默认值
      medicalHistory: elderly.value.medicalHistory || [],
      allergies: elderly.value.allergies || []
    })
    showEditDialog.value = true
  }
}

// 保存基本信息
const saveBasicInfo = async () => {
  try {
    saving.value = true
    await editFormRef.value?.validate()
    
    const response = await updateElderly(editForm.id, editForm)
    if (response.code === 200) {
      ElMessage.success('保存成功')
      // 更新本地数据
      Object.assign(elderly.value!, editForm)
      showEditDialog.value = false
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    saving.value = false
  }
}

// 病史和过敏史操作方法
const addEditMedicalHistory = () => {
  if (newEditMedicalHistory.value.trim()) {
    editForm.medicalHistory.push(newEditMedicalHistory.value.trim())
    newEditMedicalHistory.value = ''
  }
  showEditMedicalHistoryInput.value = false
}

const removeEditMedicalHistory = (index: number) => {
  editForm.medicalHistory.splice(index, 1)
}

const addEditAllergy = () => {
  if (newEditAllergy.value.trim()) {
    editForm.allergies.push(newEditAllergy.value.trim())
    newEditAllergy.value = ''
  }
  showEditAllergyInput.value = false
}

const removeEditAllergy = (index: number) => {
  editForm.allergies.splice(index, 1)
}
const healthForm = reactive({
  id: '',
  date: '',
  systolic: '',
  diastolic: '',
  bloodSugar: '',
  weight: '',
  temperature: '',
  heartRate: '',
  notes: ''
})

const medicationForm = reactive({
  id: '',
  date: '',
  medicationName: '',
  dosage: '',
  frequency: '',
  duration: '',
  doctor: '',
  status: '',
  notes: ''
})

const healthRules = {
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  'bloodPressure.systolic': [{ required: true, message: '请输入收缩压', trigger: 'blur' }],
  'bloodPressure.diastolic': [{ required: true, message: '请输入舒张压', trigger: 'blur' }],
  bloodSugar: [{ required: true, message: '请输入血糖值', trigger: 'blur' }],
  weight: [{ required: true, message: '请输入体重', trigger: 'blur' }],
  temperature: [{ required: true, message: '请输入体温', trigger: 'blur' }],
  heartRate: [{ required: true, message: '请输入心率', trigger: 'blur' }]
}

const medicationRules = {
  date: [{ required: true, message: '请选择日期', trigger: 'change' }],
  medicationName: [{ required: true, message: '请输入药品名称', trigger: 'blur' }],
  dosage: [{ required: true, message: '请输入剂量', trigger: 'blur' }],
  frequency: [{ required: true, message: '请输入频次', trigger: 'blur' }],
  duration: [{ required: true, message: '请输入疗程', trigger: 'blur' }]
}



const saveHealthRecord = async () => {
  if (!healthFormRef.value) return
  
  try {
    // 打印要提交表单数据
    console.log('健康记录表单数据:', healthForm)
    await healthFormRef.value.validate()
    
    const record = {
      ...healthForm,
      elderlyId: route.params.id as string,
      date: new Date(healthForm.date).toISOString()
    }
    
     // 打印即将发送的数据
    console.log('准备发送的健康记录数据:', record)
    
     const response = await addCheckupData(record)
     if (response.code !== 200) {
      ElMessage.error(response.message || '健康记录添加失败')
      return
    }
      
    ElMessage.success('健康记录添加成功')
    showHealthDialog.value = false
    await getHealthRecords()
    initCharts()
  } catch (error) {
    console.error('保存失败:', error)
  }
}

const saveMedicationRecord = async () => {
  if (!medicationFormRef.value) return
  
  try {
    await medicationFormRef.value.validate()
    
    const record = {
      ...medicationForm,
      elderlyId: route.params.id as string,
      date: new Date(medicationForm.date).toISOString()
    }

    const response = await addMedicationData(record)
     if (response.code !== 200) {
      ElMessage.error(response.message || '用药记录添加失败')
      return
    }
    
    ElMessage.success('用药记录添加成功')
    showMedicationDialog.value = false
    getMedicationRecords()
  } catch (error) {
    console.error('保存失败:', error)
  }
}

const deleteMedication = async (record: MedicationRecord) => {
  try {
    await ElMessageBox.confirm('确定要删除这条用药记录吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 这里应该调用API删除记录
    await deleteMedicationData(record.id);
    ElMessage.success('删除成功')
    getMedicationRecords()
  } catch {
    // 用户取消
  }
}

const resetHealthForm = () => {
  Object.assign(healthForm, {
    date: '',
     systolic: 0, 
     diastolic: 0 ,
    bloodSugar: 0,
    weight: 0,
    height: 0,
    temperature: 0,
    heartRate: 0,
    notes: ''
  })
}

const resetMedicationForm = () => {
  Object.assign(medicationForm, {
    date: '',
    medicationName: '',
    dosage: '',
    frequency: '',
    duration: '',
    notes: ''
  })
}

const initCharts = () => {
  nextTick(() => {
    console.log('initCharts1')
    if (bloodPressureChart.value && bloodSugarChart.value) {
      console.log('initCharts2')
      // 血压图表
      const bpChart = echarts.init(bloodPressureChart.value)
      const bpData = healthRecords.value.map(record => ({
        date: new Date(record.date).toLocaleDateString(),
        systolic: record.systolic,
        diastolic: record.diastolic
      }))
      
      bpChart.setOption({
        title: { text: '血压趋势', left: 'left' },

        tooltip: { trigger: 'axis' },
        legend: { data: ['收缩压', '舒张压'] },
        xAxis: { type: 'category', data: bpData.map(item => item.date) },
        yAxis: { type: 'value' },
        series: [
          {
            name: '收缩压',
            type: 'line',
            data: bpData.map(item => item.systolic)
          },
          {
            name: '舒张压',
            type: 'line',
            data: bpData.map(item => item.diastolic)
          }
        ]
      })
      
      // 血糖图表
      const bsChart = echarts.init(bloodSugarChart.value)
      const bsData = healthRecords.value.map(record => ({
        date: new Date(record.date).toLocaleDateString(),
        value: record.bloodSugar
      }))
      
      bsChart.setOption({
        title: { text: '血糖趋势', left: 'center' },
        tooltip: { trigger: 'axis' },
        xAxis: { type: 'category', data: bsData.map(item => item.date) },
        yAxis: { type: 'value' },
        series: [
          {
            name: '血糖',
            type: 'line',
            data: bsData.map(item => item.value)
          }
        ]
      })
    }
  })
}


</script>

<style scoped>
.elderly-detail {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.info-card {
  height: fit-content;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-content {
  font-size: 14px;
}
.tags-container {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
  align-items: center;
}

.no-data {
  color: #999;
  font-style: italic;
}
.info-item {
  margin-bottom: 12px;
  display: flex;
}

.info-item label {
  font-weight: 500;
  color: #666;
  min-width: 80px;
}

.info-item span {
  color: #333;
}

.tag-list {
  flex: 1;
}

.no-data {
  color: #999;
  font-style: italic;
}

.health-charts {
  
  margin-bottom: 20px;
}

.chart-container {
  height: 300px;
  margin-bottom: 20px;
}

@media (max-width: 768px) {
  .el-col {
    margin-bottom: 20px;
  }
  
  .chart-container {
    height: 250px;
  }
}
</style> 